/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*  MAY BE TOO HEACY..
function showHideDocSlide( i ) {
  var doc = $('doc'+i);
  var snippet = $('snippet'+i);

  if ( doc.style.display=='none' ) {
    if ( doc.innerHTML=='' ) {
      doc.innerHTML="Loading...";
    }
    snippet.style.display='none';//hide
    jQuery('#doc'+i).slideDown('fast', function(){//show
      
    });
  } else {
    jQuery('#doc'+i).slideUp('fast', function(){//hide
      snippet.style.display='';//show
    });
  }
}
*/

function showHideDoc( i ) {
  var doc = $('doc'+i);
  var snippet = $('snippet'+i);

  if ( doc.style.display=='none' ) {
    if ( doc.innerHTML=='' ) {
      doc.innerHTML="Loading...";
    }
    snippet.style.display='none';
    doc.style.display='';
  } else {
    snippet.style.display='';
    doc.style.display='none';
  }
}

function showHideAllDocs() {
  var i = 0;
  while ( 1 ) {
    try {
      showHideDoc( i );
    } catch (e) {
      break;
    }
    i++;
  }
}

function highlightResult( text, query ) {
  query = query.replace( /#.*?\(/g, '(' );
  query = query.replace( /\(|\)|"/g, ' ' );
  var words = query.split(" ");
  var i=0;
  for (i=0; i<words.length; i++) {
    if( words[i] != "" ) {
      var rgexp = new RegExp(words[i], "g");
      text = text.replace(rgexp, '<strong>'+words[i]+'</strong>');
    }
  }
  return text;
}

function postprocess() {
  $('indriQuery').value = $('indriQuery').value.replace(/[ 　]/g, ' ').replace(/[\n\r]+/g,'');
  
  //store query into cookie.
//  var key = top.main.document.getElementById('taskNameShort').value+'_'+top.main.document.getElementById('topicId').value;
//  setCookie(key, $('indriQuery').value);
}

function convertQuery(queryType) {
  //boolean representing whether to segment by char or not.
  //".char" means true and "" means false.
  var url = contextPath+"/search/formulateQuery.jsp";
  var querywords = $("querywords").value.replace(/[\"\n\r]+/g,"");
  var param = eval('$H({"q": "' + querywords + '", "lang": "'+lang+'", "queryType": "'+queryType+'"})').toQueryString();

  // Why don't they work?!!?
  //  var param = [];
  //  param['q'] = querywords;
  //  param['lang'] = lang;
  //  param['queryType'] = queryType;
  
  //alert(querywords+", "+lang+", "+queryType);
  if ( querywords != '' ) {
    var query = $("indriQuery");
    query.value = "Segmenting "+querywords+" ...";
    new Ajax.Request( url, {   
      method: "get",
      parameters: param, 
      onSuccess: function(request) {
        var r = request.responseText;
        query.value = r;
        query.value = query.value.replace(/[\n\r]+/g,"");
      }
    });
  }
}

// For adding an answer text by right click

var docId = "";
var answerText = "";
var begin = -1;
var end = -1;
jQuery(document).ready(function() {
  if (!! $('isStandalone').value ){
    return;
  }
  
  if ( tdLabels.length==0 && tdLabels[0].length()==0 ) {
    var a = document.createElement('a');
    a.href = 'javascript:void(0);';
    a.innerHTML = 'Add';
    var li = document.createElement('li');
    li.id = 'command_add';
    li.appendChild(a);
    $('command_list_ul').appendChild(li);
  } else {
    for (var i = 0; i < tdLabels.length; i++) {
      var a = document.createElement('a');
      a.href = 'javascript:void(0);';
      a.innerHTML = 'Add ('+tdLabels[i]+')';
      var li = document.createElement('li');
      li.id = 'command_add_'+tdLabels[i];
      li.appendChild(a);
      $('command_list_ul').appendChild(li);
    }
  }
  
  jQuery('.doc').bind('mouseup', function(e) {
    var range = rangy.getSelection().getRangeAt(0);
    if ( range.collapsed ) { return; }
    if (typeof(range) == "undefined" || !range) {return;} 

    // entireNodes
    var sumOfOffsets = 0;

    var aNode = range.getNodes()[0];
    var docDiv;
    while (aNode != document) {
      aNode = aNode.parentNode;
      if (typeof(aNode.id)!='undefined' && aNode.id.match(new RegExp('doc[0-9]+'))) {
        docDiv = aNode;
      }
    }

    var nodes1 = docDiv.childNodes;
    for (var i=0; i<nodes1.length; i++) { 
      var n = nodes1[i];
      var isTextNode = typeof(n.tagName)=='undefined';
      if (!isTextNode) {
        n = n.childNodes[0];
      }
      var t = n.textContent;
      if (n == range.startContainer) {
        begin = sumOfOffsets + range.startOffset;
      }
      if (n == range.endContainer) {
        end = sumOfOffsets + range.endOffset;
      }
      sumOfOffsets += (t ? t.length : 0);
    }
    
    var selectedText = range.toString();
    answerText = selectedText;
    docId = extractDocId( jQuery(this).html() );
    //&& $('#command_list').css('display')=='none' ??
    if (selectedText) {
      if ( e.which <= 1 ) { //left click only
        var l = e.pageX;
        var t = e.pageY;
        setTimeout(function(e){ // this trick is needed for IE!!
          if (getSelectedText()) { // unless this checking, pop-up occurs without text selection when clicked on a selection
            jQuery('#command_list').css('left', l+'px').css('top', t+'px');
            jQuery('#command_list').fadeIn('fast');
          }
        }, 10);
      }
    }
  });
  
  jQuery('#command_list_ul > li').mouseup( function() {
    top.main.document.getElementById("begin").value = begin;
    top.main.document.getElementById("end").value = end;
    top.main.document.getElementById("newAnswerText").value = answerText.replace(/(\r)?\n/g,'');
    top.main.document.getElementById("newDocId").value = docId.replace(/<.+?>/g,'');
    top.main.document.getElementById("newLabel").value = this.id.replace(/command_add_/g,'');
    top.main.addAnswerText();
    top.main.scrollDown();
    jQuery('#command_list').offset({ top: 0, left: 0 }).hide(); //hideCommandList
  });
  
  jQuery('.doc').bind('mousedown', function(e) {
    jQuery('#command_list').offset({ top: 0, left: 0 }).hide(); //hideCommandList
  });
  
  jQuery('a', '#command_list').button();
});

function extractDocId( xml ) {
  var id = "";
  
  xml.match(/&lt;TREC[_]?ID&gt;(.+?)&lt;\/TREC[_]?ID&gt;/i);
  id = RegExp.$1;
  if ( ! xml.match(/TREC/ ) ) {
    xml.match(/&lt;DOCNO&gt;(.+?)&lt;\/DOCNO&gt;/i);
    id = RegExp.$1;
  }
  //FIXME: hack!!
  if ( xml.match(/DOCNO/ ) ) {
    xml.match(/&lt;DOCNO&gt;(.+?)&lt;\/DOCNO&gt;/i);
    id = RegExp.$1;
  }
  return id;
}

function enteringWord() {
  //jQuery('input[id^="ir_convert"]').removeAttr('disabled');
}

function enteredWord(queryType) {
  convertQuery(queryType);
  postprocess();
  //jQuery('input[id^="ir_convert"]').attr('disabled',true);
}